package com.shwread.android.ui.page.chat;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.logic.bean.AddressBookInfo;
import com.ciko.code.logic.dao.AddressBookInfoDao;
import com.ciko.code.utils.PerferencesUtil;
import com.google.gson.reflect.TypeToken;
import com.shwread.address.AddressActivity;
import com.shwread.address.bean.FileBean;
import com.shwread.address.bean.Node;
import com.shwread.address.bean.QryEnterpriseBean;
import com.shwread.address.tree_view.SimpleTreeAdapter;
import com.shwread.address.tree_view.TreeListViewAdapter;
import com.shwread.android.qysw.activity.CommonWebActivity;
import com.shwread.android.qysw.activity.ContactGroupActivity;
import com.shwread.android.qysw.activity.ContactSearchActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.customview.MyExpandableListView;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.page.chat.adapter.ContactGroupAdapter;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.ContactYellowPageInfo;
import logic.bean.ContractInfo;
import logic.bean.GroupBean;
import logic.constants.DefaultConsts;
import logic.dao.GroupDao;

/**
 * 分层通讯录
 */
public class LayereContactsPage extends AbstractUIPage<MainActivity> implements OnClickListener {
    public static LayereContactsPage instance;
    public static int[] isClose;
    private PullToRefreshScrollView contentView;
    private MyExpandableListView listView;
    private TextView tvSearch;
    private RelativeLayout rlChatGroup, rlYellowPage;
    private List<GroupBean> groups = new ArrayList<>();
    private HashMap<String, List<AddressBookInfo>> contacts = new HashMap<>();
    private String ypUrl;
    private static long lastTimeStamp;
    private ProgressDialog progressDialog;
    private static final int PROGRESS_SHOW = 111;
    private static final int PROGRESS_HIDE = 112;
    private static final int REFRESH_DATA = 113;

    private ContactGroupAdapter adapter;

    //数据库相关
    private GroupDao groupDao;
    private AddressBookInfoDao addressBookInfoDao;
    private ListView mTree;

    public LayereContactsPage(MainActivity t) {
        super(t);
    }

    public static LayereContactsPage getInstance(MainActivity t) {
        if (instance == null) {
            instance = new LayereContactsPage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.chat_contact, null);
        //		String str = String.valueOf(System.currentTimeMillis());
        //		lastTimeStamp = Long.parseLong(str);
        groupDao = GroupDao.getInstance(bActivity);
        addressBookInfoDao = AddressBookInfoDao.getInstance(bActivity);
        lastTimeStamp = PerferencesUtil.getInstance(context).getContactLastTimeStamp();
        findView();
        initData();
        setMyListView();
        setListener();
        return curMyView;
    }

    private void initData() {
        NewActionHelp.qryEnterpriseAddressBookList(context, lastTimeStamp, new GetAddressBookListHandler());
        NewActionHelp.qryEnterpriseYellowPage(context, new GetYellowPageHandler());
    }

    public class GetYellowPageHandler extends ObjectHttpResponseHandler<ContactYellowPageInfo> {

        @Override
        public Type getType() {
            return new TypeToken<ContactYellowPageInfo>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {

        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, ContactYellowPageInfo arg2, String arg3) {
            if (arg2 != null) {
                ypUrl = arg2.getUrl();
            }
        }
    }

    public class GetAddressBookListHandler extends ObjectHttpResponseHandler<ContractInfo> {

        @Override
        public Type getType() {
            return new TypeToken<ContractInfo>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
        }

        @Override
        public void onSuccess(final int arg0, Header[] arg1, final ContractInfo arg2, String arg3) {
            lastTimeStamp = arg2.getLastTimeStamp();
            PerferencesUtil.getInstance(context).setContactLastTimeStamp(lastTimeStamp);
            if (arg2.getGroupList() != null && arg2.getGroupList().size() > 0) {
                new Thread() {
                    @Override
                    public void run() {
                        groups = arg2.getGroupList();
                        putDataToDB();
                    }
                }.start();
            }
        }

    }

    private void sortContacts() {
        List<AddressBookInfo> contacts;
        AddressBookInfo contact;
        for (GroupBean group : groups) {
            contacts = group.getAddressBookList();
            for (int i = 0; i < contacts.size() - 1; i++) {
                for (int j = i; j < contacts.size(); j++) {
                    if (contacts.get(i).getSortNum() > contacts.get(j).getSortNum()) {
                        contact = contacts.get(i);
                        contacts.set(i, contacts.get(j));
                        contacts.set(j, contact);
                    }
                }
            }
            group.setAddressBookList(contacts);
        }
    }

    private void sortGroups() {
        GroupBean bean;
        for (int i = 0; i < groups.size() - 1; i++) {
            for (int j = i + 1; j < groups.size(); j++) {
                if (groups.get(i).getSortNum() < groups.get(j).getSortNum()) {
                    bean = groups.get(i);
                    groups.set(i, groups.get(j));
                    groups.set(j, bean);
                }
            }
        }
    }

    private void getDataFromDb() {
        groups.clear();
        List<GroupBean> dbGroups;
        dbGroups = groupDao.getAll();
        for (int i = 0; i < dbGroups.size(); i++) {
            List<AddressBookInfo> addressBookList = new ArrayList<>();
            List<AddressBookInfo> dbList;
            dbList = addressBookInfoDao.getListByGroupId(dbGroups.get(i).getGroupId());
            if (dbList != null && dbList.size() != 0) {
                for (AddressBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n")) {
                        addressBookList.add(info);
                    }
                }
            }
            dbGroups.get(i).setAddressBookList(addressBookList);
        }
        for (GroupBean group : dbGroups) {
            if (group.getAddressBookList() != null && group.getAddressBookList().size() != 0) {
                groups.add(group);
            }
        }
    }

    private void putDataToDB() {
        handler.sendEmptyMessage(PROGRESS_SHOW);
        //		groupDao.addList(groups);
        for (GroupBean group : groups) {
            if (groupDao.getById(group.getGroupId()) != null) {
                groupDao.update(group);
            } else {
                groupDao.add(group);
            }
            if (group.getAddressBookList() == null) {
                continue;
            }
            for (AddressBookInfo addressBookInfo : group.getAddressBookList()) {
                if (addressBookInfoDao.getById(addressBookInfo.getContactId(), group.getGroupId()) != null) {
                    addressBookInfoDao.update(addressBookInfo);
                } else {
                    addressBookInfoDao.add(addressBookInfo);
                }
            }
            //			addressBookInfoDao.addList(group.getAddressBookList());
        }
        handler.sendEmptyMessage(PROGRESS_HIDE);
//        handler.sendEmptyMessage(REFRESH_DATA);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PROGRESS_SHOW:
                    progressDialog = ProgressDialog.show(bActivity, "", "正在初始化通讯录...");
                    break;
                case PROGRESS_HIDE:
                    progressDialog.dismiss();
                    break;
                case REFRESH_DATA:
                    getDataFromDb();
                    sortGroups();
                    sortContacts();
                    int p = 0;
                    isClose = new int[groups.size()];
                    for (GroupBean group : groups) {
                        List<AddressBookInfo> list = new ArrayList<>();
                        if (group.getAddressBookList().size() > 50) {
                            for (int i = 0; i < 50; i++) {
                                list.add(group.getAddressBookList().get(i));
                            }
                        } else {
                            list.addAll(group.getAddressBookList());
                        }
                        contacts.put(group.getName(), list);
                        isClose[p] = 0;
                        p++;
                    }
                    Collections.reverse(groups);
                    adapter = new ContactGroupAdapter(context, listView, groups, contacts);
//					listView.setAdapter(adapter);
                    listView.setGroupIndicator(null);
                    listView.setFocusable(false);
                    listView.setFocusableInTouchMode(false);
                    contentView.onRefreshComplete();
                    listView.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    private void setListener() {
        rlYellowPage.setOnClickListener(this);
        rlChatGroup.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
        contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown()) {
                    refrush();
                } else if (contentView.isFooterShown()) {
//                    boolean isAllClose = true;
//                    int i;
//                    for (i = 0; i < isClose.length; i++) {
//                        if (isClose[i] == 1) {
//                            isAllClose = false;
//                            break;
//                        }
//                    }
//                    if (!isAllClose) {
//                        GroupBean group = groups.get(i);
//                        List<AddressBookInfo> list = contacts.get(group.getName());
//                        if (list.size() < group.getAddressBookList().size()) {
//                            int size = list.size();
//                            for (int j = list.size(); j < group.getAddressBookList().size() && j < size + 50; j++) {
//                                list.add(group.getAddressBookList().get(j));
//                            }
//                            contacts.put(group.getName(), list);
////							adapter.notifyDataSetChanged();
//                        }
//                    }
                    contentView.onRefreshComplete();
                }
            }

        });
    }

    /**
     * 下拉刷新
     */
    private void refrush() {
        listView.setVisibility(View.GONE);
        initData();
        setMyListView();
    }

    private void findView() {
        contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.contact_psview);
        PullToRefreshUtil.initLabel(bActivity, contentView);
        tvSearch = (TextView) curMyView.findViewById(R.id.et_contact_search);
        rlChatGroup = (RelativeLayout) curMyView.findViewById(R.id.rl_chat_groups);
        rlYellowPage = (RelativeLayout) curMyView.findViewById(R.id.rl_chat_yellow_page);
        listView = (MyExpandableListView) curMyView.findViewById(R.id.contacts_list);

        mTree = (ListView) curMyView.findViewById(R.id.id_tree);
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        contentView.getRefreshableView().smoothScrollTo(0,0);
//        		initData();
        SessionPage.isFirstIn = 1;
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_chat_yellow_page:
                Intent ypIntent = new Intent(bActivity, CommonWebActivity.class);
                ypIntent.putExtra(DefaultConsts.title_s, "电话黄页");
                ypIntent.putExtra(DefaultConsts.req_url_s, ypUrl);
                bActivity.startActivity(ypIntent);
                break;

            case R.id.rl_chat_groups:
                Intent groupIntent = new Intent(bActivity, ContactGroupActivity.class);
                groupIntent.putExtra("fromType", "contactList");
                //				Intent groupIntent = new Intent(bActivity, ContactMainActivity.class);
                bActivity.startActivity(groupIntent);
                break;
            case R.id.et_contact_search:
                Intent searchIntent = new Intent(bActivity, ContactSearchActivity.class);
                bActivity.startActivity(searchIntent);
                break;
            default:
                break;
        }
    }

    private TreeListViewAdapter mAdapter;
    private List<FileBean> mDatas;

    /**
     * 获取分层通讯录数据
     */
    private void setMyListView() {
        NewActionHelp.qryEnterpriseGroupLevelist(bActivity, new ObjectHttpResponseHandler<List<QryEnterpriseBean>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("111111failure", "String:" + s);
                contentView.onRefreshComplete();
            }

            @Override
            public void onSuccess(int i, Header[] headers, List<QryEnterpriseBean> qryEnterpriseBeans, String s) {
                Log.e("111111ok", "String:" + s);
                contentView.onRefreshComplete();
                mDatas = new ArrayList<>();
                initContactData(qryEnterpriseBeans);
                setAdapter();
            }

            @Override
            public Type getType() {
                return new TypeToken<List<QryEnterpriseBean>>() {
                }.getType();
            }
        });
    }

    /**
     * 设置listView数据填充
     */
    private void setAdapter() {
        try {
            mAdapter = new SimpleTreeAdapter<>(mTree, bActivity, mDatas, 0);//0代表全部不展开
            mAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                @Override
                public void onClick(Node node, int position) {//点击事件
                    if (node.isLeaf()) {//叶子节点
                        Intent intent = new Intent(bActivity, AddressActivity.class);
                        intent.putExtra("groupId", node.getId());
                        bActivity.startActivity(intent);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTree.setAdapter(mAdapter);
    }

    /**
     * 转换数据
     */
    private void initContactData(List<QryEnterpriseBean> qryEnterpriseBeans) {
        for (QryEnterpriseBean bean : qryEnterpriseBeans) {
            mDatas.add(new FileBean(bean));
            List<QryEnterpriseBean> list = bean.getList();
            if (list != null && list.size() != 0) {
                initContactData(list);
            }
        }
    }
}
